
export function addIndent2em () {
  tinymce.PluginManager.add('indent2em', function(editor, url) {
    const pluginName='首行缩进'
    const global$1 = tinymce.util.Tools.resolve('tinymce.util.Tools')
    const indent2em_val = editor.getParam('indent2em_val', '2em')
    editor.on('init', function() {
      editor.formatter.register({
        indent2em: {
          selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table',
          styles: { 'text-indent': '%value' },
        }
      })
    })
    function _indent2$getValue( key, str ) {
      const m = str.match( new RegExp(key + ':?(.+?)"?[}]') )
      return m ? m[ 1 ] : false
    }
    const doAct = function () {
      editor.undoManager.transact(function(){
        editor.focus()
        const dom = editor.dom
        const blocks = editor.selection.getSelectedBlocks()
        let act = ''
        global$1.each(blocks, function (block) {
          let kv = ""
          let kl = ""
          if(block&&block.children['0']&&block.children['0'].attributes&&block.children['0'].attributes.style){
            kv = _indent2$getValue('font-size',block.children['0'].attributes.style.textContent)
            kl = _indent2$getValue('letter-spacing',block.children['0'].attributes.style.textContent)
            if(kv) {kv=(parseInt(kv)+parseInt((kl?kl:0)))*2+'px'}
            else kv=(parseInt((kl?kl:0))+16)*2+'px'
          }
          if(act==''){
            act = dom.getStyle(block,'text-indent') == (indent2em_val!='2em'?indent2em_val:kv?kv:'2em') ? 'remove' : 'add'
          }
          if( act=='add'){
            dom.setStyle(block, 'text-indent',indent2em_val!='2em'?indent2em_val:kv?kv:'2em')
          }else{
            let style=dom.getAttrib(block,'style')
            const reg = new RegExp('text-indent?(.+?)"?[}]', 'ig')
            style = style.replace(reg, '')
            dom.setAttrib(block,'style',style)
          }
        })
      })
    }
    editor.ui.registry.getAll().icons.indent2em || editor.ui.registry.addIcon('indent2em','<svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" width="24" height="24"><path d="M170.666667 563.2v-102.4H887.466667v102.4zM170.666667 836.266667v-102.4H887.466667v102.4zM512 290.133333v-102.4H887.466667v102.4zM238.933333 341.333333V136.533333l204.8 102.4z" fill="#2c2c2c" p-id="5210"></path></svg>')

    const stateSelectorAdapter = function (editor, selector) {
      return function (buttonApi) {
        return editor.selection.selectorChangedWithUnbind(selector.join(','), buttonApi.setActive).unbind
      }
    }
    editor.ui.registry.addToggleButton('indent2em', {
      icon: 'indent2em',
      tooltip: pluginName,
      onAction: function () {
        doAct()
      },
      onSetup: stateSelectorAdapter(editor, [
        '*[style*="text-indent"]',
        '*[data-mce-style*="text-indent"]',
      ])
    })
    editor.ui.registry.addMenuItem('indent2em', {
      text: pluginName,
      onAction: function() {
        doAct()
      }
    })
    editor.addCommand('indent2em', doAct  )
    return {
      getMetadata: function () {
        return  {
          name: pluginName,
          url: "https://github.com/Five-great/tinymce-plugins",
        }
      }
    }
  })
}

export function addMaxLimit(maxWord = 50000, maxMessage = '超出最大输入字符数量') {
  const tinymce = window.tinymce
  tinymce.PluginManager.add('wordlimit', function (editor) {
    const pluginName = '字数限制'
    const app = tinymce.util.Tools.resolve('tinymce.util.Delay')
    const Tools = tinymce.util.Tools.resolve('tinymce.util.Tools')
    const wordlimit_event = editor.getParam('ax_wordlimit_event', 'SetContent Undo Redo Keyup input paste')
    const options = editor.getParam('wordlimit', {}, 'object')
    let close = null
    const toast = function (message) {
      close && close.close()
      close = editor.notificationManager.open({
        text: message,
        type: 'error',
        timeout: 3000,
      })
      return
    }
    // 默认配置
    const defaults = {
      max: maxWord, // 最多可以输入多少字
      spaces: true, // 是否含空格
      isInput: false, // 是否在超出后还可以输入
      maxMessage,
      changeCallback: () => { }, // 自定义的回调方法
      changeMaxCallback: () => { },
      toast // 提示弹窗
    }

    class WordLimit {
      constructor(editor, options) {
        options = Tools.extend(defaults, options)
        let preCount = 0
        let _wordCount = 0
        let oldContent = editor.getContent()
        const WordCount = editor.plugins.wordcount
        const sumLetter = function (html) {
          const re1 = new RegExp("<.+?>", "g")
          let txt = html.replace(re1, '')
          txt = txt.replace(/\n/g, '')
          txt = txt.replace(/&nbsp/g, ' ')
          return { txt: txt, html }
        }
        editor.on(wordlimit_event, function (e) {
          const content = editor.getContent() || e.content || ''
          if (!options.spaces) {
            // 字数
            _wordCount = WordCount.body.getCharacterCount()
          } else {
            // 不含空格字数
            _wordCount = WordCount.body.getCharacterCountWithoutSpaces()
          }
          // options.changeCallback({ ...options, editor, num: _wordCount, content, ...sumLetter(content) })
          options.changeCallback(Object.assign({}, options, {editor, num: _wordCount, content}, sumLetter(content)))
          if (_wordCount > options.max) {
            preCount = _wordCount
            // 禁止再输入
            if (options.isInput == !1) {
              // 内容超出还原
              editor.setContent(oldContent)
              // 还原后重新统计
              if (!options.spaces) {
                _wordCount = WordCount.body.getCharacterCount()
              } else {
                _wordCount = WordCount.body.getCharacterCountWithoutSpaces()
              }
            }
            editor.getBody().blur()
            editor.fire('wordlimit', {
              maxCount: options.max,
              wordCount: _wordCount,
              preCount: preCount,
              isPaste: (e.type === 'paste' || e.paste) || false
            })
            toast(options.maxMessage)
          }
          oldContent = editor.getContent()
        })
      }
    }
    const setup = function () {
      // 如果没设置最大输入限制，则不进行下一步操作
      if (!options && !options.max) return false
      // 如果没有配置字数统计，则不进行下一步，并且提示配置字数统计
      if (!editor.plugins.wordcount) return toast('请先在tinymce的plugins配置wordlimit之前加入wordcount插件')
      app.setEditorTimeout(editor, function () {
        const editDom = editor.getContainer()
        const wordNum = editDom.querySelector("button.tox-statusbar__wordcount")
        if (wordNum && wordNum.innerText && wordNum.innerText.indexOf('字符') === -1) wordNum.click()
        new WordLimit(editor, options)
      }, 300)
    }
    setup()
    return {
      getMetadata: function () {
        return { name: pluginName }
      }
    }
  })
}

/* 插件案列
export function addUploader (action = () => {}) {
  tinymce.PluginManager.add('uploader', function(editor, url) {
    const pluginName = '上传'
    editor.ui.registry.getAll().icons.uploader || editor.ui.registry.addIcon('uploader','<svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" width="24" height="24"><path d="M170.666667 563.2v-102.4H887.466667v102.4zM170.666667 836.266667v-102.4H887.466667v102.4zM512 290.133333v-102.4H887.466667v102.4zM238.933333 341.333333V136.533333l204.8 102.4z" fill="#2c2c2c" p-id="5210"></path></svg>')

    editor.ui.registry.addButton('uploader',{
      text: '上传',
      icon: 'uploader',
      onAction:function(){
        action()
      }

    });
    return {
      getMetadata: function () {
        return  {
          name: pluginName,
          url: "https://github.com/Five-great/tinymce-plugins",
        }
      }
    }
  })
}
 */
